<?php
namespace Common\Models;
use Common\BaseModel;
use Common\Common;

class User extends BaseModel
{
    public $res;
    public $redis_key = "user_";
    public $rate = 0;

    public function initialize()
    {
        parent::initialize();
        $this->setSource('f_users');
    }


    //获取用户信息
    public function get_info($user_id)
    {
        $user_info = $this->find_by_id($user_id);
        if (empty($user_info)) {
            return [];
        }
        $user_info         = $user_info->toarray();
        $MoneyDistribution = new AppConfig();
        //获取用户应该分的钱
        $res = $MoneyDistribution->get_user_money($user_info['level_id']);
        $user_info = array_merge($res, $user_info);
        $FUserExtendsDb = new FUsersExtend();
        $fuserExtend = $FUserExtendsDb->findFirstByUserId($user_id);
        if($fuserExtend){
           $fuserExtend = $fuserExtend->toarray();
            $user_info = array_merge($fuserExtend, $user_info);
        }
        return $user_info;
    }

    public function details($where = '1=1', $columns = '*')
    {
        $data = [];
        $data = $this::findFirst(
            array(
                'conditions' => $where,
                "columns"    => $columns,
            )
        );
        return $data ? $data->toarray() : [];
    }


    public function find_by_id($id)
    {
        return $this->findFirstById($id);
    }

    public function find_by_id_columns($id, $columns)
    {
        $conditions['conditions'] = "id = $id and is_disable = 0";
        $conditions['columns']    = $columns;
        return $this->findFirst($conditions);
    }

    /**
     * @func 根据手机号获取用户的信息
     */
    public function find_by_phone($phone)
    {
        $user_info = $this->findFirstByPhone($phone);
        if (!$user_info) {
            return false;
        } else {
            return $user_info->toarray();
        }
    }

    /**
     * @func 根据手机号获取用户的信息
     */
    public function find_by_phone_info($phone)
    {
        $conditions['conditions'] = "phone  = '$phone' or invite_code = '$phone' or exclusive_code = '$phone'";
        $user_info = $this->findFirst($conditions);
        if (!$user_info) {
            return false;
        } else {
            return $user_info->toarray();
        }
    }

    /**
     * @func 根据用户id获取用户信息
     */
    public function find_by_firstId($user_id)
    {
        $user_info = $this->findFirstById($user_id);
        if (!$user_info) {
            return false;
        } else {
            return $user_info->toarray();
        }
    }


    /**
     * @func 根据微信的openid获取用户的信息
     */
    public function find_by_wxaccount($phone)
    {
        $user_info = $this->findFirstByWxAccount($phone);
        if (!$user_info) {
            return false;
        } else {
            return $user_info->toarray();
        }
    }


    /**
     * func 根据微信删除openid获取用户的信息
     * @return bool
     */
    public function find_by_wxaccountobj($phone)
    {
        $user_info = $this->findFirstByWxAccount($phone);
        return $user_info;
    }


    /**
     * @func 根据邀请码获取用户
     */
    public function find_by_inviteCode($invite_code)
    {
        if(is_numeric($invite_code)){
            $conditions['conditions'] = "invite_code = {$invite_code} or  phone = '{$invite_code}' or exclusive_code={$invite_code}";
        }else{
            $conditions['conditions'] = "invite_code = '{$invite_code}' or  phone = '{$invite_code}' or exclusive_code='{$invite_code}'";
        }
        $user_info = $this->findFirst($conditions);
        if (!$user_info) {
            return false;
        } else {
            return $user_info->toarray();
        }
    }


    /**
     * @func 更新/插入数据
     * @param $data要更新或者要插入的数据
     * @return boolean 插入成功的结果
     */
    public function save_user($data)
    {
        $data['updated_at'] = date('Y-m-d H:i:s', time());
        $result             = $this->save($data);
        return $result;
    }


    /**
     * 查询用户直属总监数量
     * @param $user_id 当前用户的id
     *
     */
    public function director_vip($user_id)
    {
        $conditions  = "referer_id = ?1 AND level_id = 3";
        $parameters  = array(1 => $user_id);
        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
            "bind"   => $parameters
        ));
        return $count_array;
    }

    /**
     * @func 查询用户的粉丝列表
     * @param $data ['type'] 1 潜在粉丝 2 直推粉丝 3 推荐粉丝
     */
    public function listByWhere($user_id, $data, $page_size = 10, $page = 1, $method = '')
    {
        $conditions = '';

        $order = '';
        if (isset($data['team_scale']) && !empty($data['team_scale'])) {
            if ($order) {
                $order .= ",team_scale " . $data['team_scale'];
            } else {
                $order .= "team_scale " . $data['team_scale'];
            }
        }

        if (isset($data['jointime']) && !empty($data['jointime'])) {
            if ($order) {
                $order .= ",created_at " . $data['jointime'];
            } else {
                $order .= "created_at " . $data['jointime'];
            }
        }

        if (!$order) {
            $order = 'id DESC';
        }

        if ($data['keyword']) {
            $conditions   .= "(nickname LIKE '%{$data['keyword']}%' OR phone='{$data['keyword']}' OR wx_nickname='{$data['keyword']}') AND ";
            $data['type'] = 2;      //只能搜索type为2的类型 直邀粉丝
        }


        if (!empty($data['level_id'])) {
            $conditions .= "level_id = {$data['level_id']} AND ";
        }

        switch ($data['type']) {
            case 1:
                $conditions .= "is_appuser = 0 AND referer_id = {$user_id}";
                break;
            case 2:
                $conditions .= "referer_id = {$user_id}";

                break;
            case 3://推荐粉丝
                $conditions .= "path like '{$data['path']}%'";
                break;
            default:
                $conditions .= "(referer_id = {$user_id} OR path like '{$data['path']},{$user_id}%')";
        }

        if (isset($data['created_at']) && !empty($data['created_at'])) {
            if ($conditions) {
                $conditions .= " AND created_at>='{$data['created_at']['start_at']}' AND created_at<='{$data['created_at']['end_at']}'";
            } else {
                $conditions = "created_at>='{$data['created_at']['start_at']}' AND created_at<='{$data['created_at']['end_at']}'";
            }
        }
        if (empty($method)) {
            $user_list = $this::find(
                array(
                    $conditions,
                    "order"  => $order,
                    "limit"  => $page_size,
                    //"columns"=>'nickname,avatar,created_at', //先不删
                    "offset" => ($page - 1) * $page_size,
                )
            );

        } else {
            $user_list = $this::count(
                array(
                    $conditions,
                    "order"  => $order,
                    "column" => 'id',
                )
            );
        }
        return $user_list;
    }




    /**
     * @func 查询用户的粉丝列表
     * @param $data ['type'] 1 潜在粉丝 2 直推粉丝 3 推荐粉丝
     */
    public function listByWhere_self($user_id, $data, $page_size = 10, $page = 1, $method = '')
    {
        $conditions = '';

        $order = '';
        if (isset($data['team_scale']) && !empty($data['team_scale'])) {
            if ($order) {
                $order .= ",team_scale " . $data['team_scale'];
            } else {
                $order .= "team_scale " . $data['team_scale'];
            }
        }

        if (isset($data['jointime']) && !empty($data['jointime'])) {
            if ($order) {
                $order .= ",created_at " . $data['jointime'];
            } else {
                $order .= "created_at " . $data['jointime'];
            }
        }

        if (!$order) {
            $order = 'id DESC';
        }

        if ($data['keyword']) {
            $conditions   .= "(nickname LIKE '%{$data['keyword']}%' OR phone='{$data['keyword']}' OR wx_nickname='{$data['keyword']}') AND ";
            $data['type'] = 2;      //只能搜索type为2的类型 直邀粉丝
        }


        if (!empty($data['level_id'])) {
            $conditions .= "level_id = {$data['level_id']} AND ";
        }

        switch ($data['type']) {
            case 1:
                $conditions .= "is_appuser = 0 AND referer_id = {$user_id}";
                break;
            case 2:
                $conditions .= "referer_id = {$user_id}";

                break;
            case 3://推荐粉丝
                $conditions .= "path like '{$data['path']}%'";
                break;
            default:
                $conditions .= "(referer_id = {$user_id} OR path like '{$data['path']},{$user_id}%')";
        }

        if (isset($data['created_at']) && !empty($data['created_at'])) {
            if ($conditions) {
                $conditions .= " AND created_at>='{$data['created_at']['start_at']}' AND created_at<='{$data['created_at']['end_at']}'";
            } else {
                $conditions = "created_at>='{$data['created_at']['start_at']}' AND created_at<='{$data['created_at']['end_at']}'";
            }
        }
        if (empty($method)) {
            $user_list = $this::find(
                array(
                    $conditions,
                    "order"  => $order,
                    "limit"  => $page_size,
                    "columns"=>'id,phone,avatar,nickname,wx_nickname,created_at', //先不删
                    "offset" => ($page - 1) * $page_size,
                )
            );

        } else {
            $user_list = $this::count(
                array(
                    $conditions,
                    "order"  => $order,
                    "column" => 'id',
                )
            );
        }
        return $user_list;
    }





    /**
     * @func 查询用户的粉丝列表
     * @param $data ['type'] 1 潜在粉丝 2 直推粉丝 3 推荐粉丝
     */
    public function listByWherenew($user_id, $data, $page_size = 10, $page = 1, $method = '')
    {
        $conditions = '';

        $order = '';
        if (isset($data['team_scale']) && !empty($data['team_scale'])) {
            if ($order) {
                $order .= ",team_scale " . $data['team_scale'];
            } else {
                $order .= "team_scale " . $data['team_scale'];
            }
        }

        if (isset($data['jointime']) && !empty($data['jointime'])) {
            if ($order) {
                $order .= ",created_at " . $data['jointime'];
            } else {
                $order .= "created_at " . $data['jointime'];
            }
        }

        if (!$order) {
            $order = 'id DESC';
        }

        if ($data['keyword']) {
            $conditions   .= "(nickname LIKE '%{$data['keyword']}%' OR phone='{$data['keyword']}') AND ";
            $data['type'] = 2;      //只能搜索type为2的类型 直邀粉丝
        }


        if (!empty($data['level_id'])) {
            $conditions .= "level_id = {$data['level_id']} AND ";
        }

        switch ($data['type']) {
            case 1:
                $conditions .= "is_appuser = 0 AND referer_id = {$user_id}";
                break;
            case 2:
                $conditions .= "referer_id = {$user_id}";

                break;
            case 3://推荐粉丝
                $conditions .= "path like '{$data['path']}%'";
                break;
            default:
                $conditions .= "(referer_id = {$user_id} OR path like '{$data['path']},{$user_id}%')";
        }

        if (isset($data['created_at']) && !empty($data['created_at'])) {
            if ($conditions) {
                $conditions .= " AND created_at>='{$data['created_at']['start_at']}' AND created_at<='{$data['created_at']['end_at']}'";
            } else {
                $conditions = "created_at>='{$data['created_at']['start_at']}' AND created_at<='{$data['created_at']['end_at']}'";
            }
        }


        if(isset($data['is_appuser'])){
            if($conditions){
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            }else{
                $conditions = "is_appuer={$data['is_appuser']}";
            }
        }


        if (empty($method)) {
            $user_list = $this::find(
                array(
                    $conditions,
                    "order"   => $order,
                    "limit"   => $page_size,
                    "columns" => 'id,avatar,phone,wx_nickname,nickname,created_at,referer_id',
                    "offset"  => ($page - 1) * $page_size,
                )
            );

        } else {
            $user_list = $this::count(
                array(
                    $conditions,
                    "order"  => $order,
                    "column" => 'id',
                )
            );
        }
        return $user_list;
    }


    /**
     * @func 根据邀请码获取用户
     */
    public function find_by_pathList($path)
    {
        $conditions['conditions'] = "id in ($path)";
        $conditions['columns']    = "id,growth_value,level_id";
        $data                     = $this->find($conditions);
        if (!$data) {
            return false;
        } else {
            return $data->toarray();
        }
    }

    /**
     * @func 查询某时间段邀请粉丝数量（直邀与间接）
     * @param $path 用户的路径
     * @param $data 时间筛选
     */
    public function getInviteFansCount($user_id, $path, $data)
    {
        $path = $path . ',' . $user_id;
        if ($data['start_end_time']) {
            $conditions = "(referer_id = {$user_id} Or path LIKE '{$path}%') AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
        } else {
            $conditions = "(referer_id = {$user_id} OR path like '{$path}%')";//referer_id = ?1 Or path LIKE ?2
        }
        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= ' AND is_buyed=1';
            } else {
                $conditions .= 'is_buyed=1';
            }
        }
        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
        ));
        return $count_array;
    }

    /**
     * 查询直接邀请粉丝数量（直邀）
     */
    public function getDirectFansCount($user_id, $data)
    {
        if (isset($data['start_end_time']) && !empty($data['start_end_time'])) {
            $conditions = "referer_id = {$user_id} AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
        } else {
            $conditions = "referer_id = {$user_id}";
        }
        if (isset($data['is_appuser']) && !empty($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions = "is_appuser={$data['is_appuser']}";
            }
        }
        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= " AND is_buyed={$data['is_buyed']}";
            } else {
                $conditions .= " is_buyed={$data['is_buyed']}";
            }
        }


        if (isset($data['level_id'])) {
            if ($conditions) {
                $conditions .= " AND level_id={$data['level_id']}";
            } else {
                $conditions = "level_id={$data['level_id']}";
            }
        }


        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
        ));
        return $count_array;
    }


    /**
     * 获取直接邀请粉丝id（直邀）
     */
    public function getDirectFansfind($user_id, $data)
    {
        if ($data['start_end_time']) {
            $conditions = "referer_id = {$user_id} AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
        } else {
            $conditions = "referer_id = {$user_id}";
        }
        if (isset($data['is_appuser']) && !empty($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions = "is_appuser={$data['is_appuser']}";
            }
        }
        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= " AND is_buyed={$data['is_buyed']}";
            } else {
                $conditions .= " is_buyed={$data['is_buyed']}";
            }
        }
        $count_array = $this:: find(array(
            $conditions,
            "columns" => "id",
        ))->toarray();
        if ($count_array) {
            $ids = '';
            foreach ($count_array as $key => $value) {
                $ids .= $value['id'] . ',';
            }
            $ids = substr($ids, 0, strlen($ids) - 1);
            return $ids;
        } else {
            return -1;
        }
    }


    /**
     * 查询直接邀请粉丝列表
     */
    public function getDirectFansList($user_id, $data)
    {
        if ($data['start_end_time']) {
            $conditions = "referer_id = {$user_id} AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
        } else {
            $conditions = "referer_id = {$user_id}";
        }
        if (isset($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions = "is_appuser={$data['is_appuser']}";
            }
        }
        if (isset($data['ids'])) {
            if ($conditions) {
                $conditions .= " AND id in({$data['ids']})";
            } else {
                $conditions = "id in({$data['ids']})";
            }
        }
        $count_array = $this:: find(array(
            $conditions,
        ))->toarray();
        return $count_array;
    }


    /**
     * 查询直接邀请粉丝数量（直邀） 只对当前登录过的用户
     */
    public function getDirectFansCount_isappuser($user_id, $data)
    {
        if ($data['start_end_time']) {
            $conditions = "referer_id = ?1 AND created_at >= ?2 AND created_at < ?3";
            $parameters = array(1 => $user_id, 2 => $data['start_end_time']['start_at'], 3 => $data['start_end_time']['end_at']);
        } else {
            $conditions = "referer_id = ?1 AND is_appuser=1";
            $parameters = array(1 => $user_id);
        }
        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
            "bind"   => $parameters
        ));
        return $count_array;
    }


    /**
     * 查询间接邀请粉丝数量（间接）
     */
    public function getIndirectFansCount($user_id, $path, $data = [])
    {
        $path       = $path . ',' . $user_id;
        $conditions = "path LIKE '{$path}%'";// AND referer_id <> $user_id
        if (isset($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions .= " is_appuser={$data['is_appuser']}";
            }
        }

        if (isset($data['start_end_time']) && !empty($data['start_end_time'])) {
            if ($conditions) {
                $conditions .= " AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
            } else {
                $conditions = "created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
            }
        }


        if (isset($data['level_id'])) {
            if ($conditions) {
                $conditions .= " AND level_id={$data['level_id']}";
            } else {
                $conditions = "level_id={$data['level_id']}";
            }
        }


        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= " AND is_buyed={$data['is_buyed']}";
            } else {
                $conditions .= " is_buyed={$data['is_buyed']}";
            }
        }
        $count_array = $this:: count(array(
            $conditions,
            "column" => "id",
        ));
        return $count_array;
    }


    /**
     * 查询间接邀请粉丝数量（间接）
     */
    public function getIndirectFansCount_find($user_id, $path, $data = [])
    {
        if ($path != -1) {
            $path       = $path . ',' . $user_id;
            $conditions = "path LIKE '{$path}%'";// AND referer_id <> $user_id
        } else {
            $conditions = "referer_id={$user_id}";
        }

        if (isset($data['is_appuser'])) {
            if ($conditions) {
                $conditions .= " AND is_appuser={$data['is_appuser']}";
            } else {
                $conditions .= " is_appuser={$data['is_appuser']}";
            }
        }

        if (isset($data['start_end_time']) && !empty($data['start_end_time'])) {
            if ($conditions) {
                $conditions .= " AND created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
            } else {
                $conditions = "created_at >= '{$data['start_end_time']['start_at']}' AND created_at < '{$data['start_end_time']['end_at']}'";
            }
        }

        if (isset($data['level_id'])) {
            if ($conditions) {
                $conditions .= " AND level_id >=  {$data['level_id']}";
            } else {
                $conditions = "level_id  >= {$data['level_id']}";
            }
        }

        if (isset($data['is_buyed'])) {
            if ($conditions) {
                $conditions .= " AND is_buyed={$data['is_buyed']}";
            } else {
                $conditions .= " is_buyed={$data['is_buyed']}";
            }
        }
        $count_array = $this:: find(array(
            $conditions,
            "columns" => "id",
        ));
        $ids_arr     = $count_array->toarray();
        if ($ids_arr) {
            $ids = '';
            foreach ($ids_arr as $key => $value) {
                $ids .= $value['id'] . ',';
            }
            $ids = substr($ids, 0, strlen($ids) - 1);
            return $ids;
        } else {
            return -1;
        }
    }


    public function get_user_id_by_tbrid($rid)
    {
        $condition = ['conditions' => "tb_rid ='$rid'", 'columns' => '*'];
        return $this->findFirst($condition);
    }

    /*
	 通过淘宝rid返回用户id数组
	 */
    public function get_user_id_by_tb_rid($pid_arr)
    {
        $ids = '';
        foreach ($pid_arr as $k => $v) {
            if ($k == 0) {
                $ids = $v;
            } else {
                $ids .= ',' . $v;
            }
        }
        $arr       = [];
        $condition = ['conditions' => "tb_rid in($ids)", 'columns' => 'tb_rid,id'];
        $res       = @$this->find($condition);
        foreach ($res->toarray() as $k => $v) {
            $arr[$v['tb_rid']] = $v['id'];
        }
        return $arr;
    }

    /*
	 通过拼多多返回用户id
	 */
    public function get_user_id_by_pdd_pid($pid_arr)
    {
        $ids = '';
        foreach ($pid_arr as $k => $v) {
            if ($k == 0) {
                $ids = "'" . $v . "'";
            } else {
                $ids .= ",'" . $v . "'";
            }
        }
        $condition = ['conditions' => "pdd_pid in($ids)", 'columns' => 'pdd_pid,id'];
        $res       = $this->find($condition);
        foreach ($res->toarray() as $k => $v) {
            $arr[$v['pdd_pid']] = $v['id'];
        }
        return $arr;
    }

    //使用户有效
    public function update_user_enable($user_id)
    {
        $user_info  = $this->findFirstById($user_id);
        $res['res'] = false;
        if ($user_info) {
            if ($user_info->is_buyed == 0) {
                $user_info->is_buyed = 1;
                $res['res']          = true;
                $res['referer_id']   = $user_info->referer_id;
                $res['path']         = $user_info->path;
                $user_info->save();
            }
        }
        return $res;

    }

//通过淘宝rid招人
    public function find_by_id_rid_find($tb_rid)
    {
        $info = $this->findFirstByTbRid($tb_rid);
        if ($info) {
            return $info->toarray();
        } else {
            return [];
        }
    }

    //获取粉丝最近直邀人的注册时间
    public function get_fans_near_reg($user_id)
    {
        $condition['conditions'] = "referer_id = $user_id";
        $condition['order']      = 'id desc';
        $condition['columns']    = "created_at";
        $res                     = $this->findFirst($condition);
        if ($res == false) {
            return '';
        }
        return $res->created_at;
    }

    //获取导师微信号
    public function get_tutor($user_id)
    {
        $condition['conditions'] = "id=$user_id";
        $condition['columns']    = 'referer_id,path';
        $res                     = $this->findFirst($condition)->toarray();
        $path                    = $res['path'] . ',' . $res['referer_id'];
        $condition['conditions'] = "id  in ($path) and is_tutor =1";
        $condition['columns']    = 'id,weixin_no as weChatNumber,nickname as name,avatar as coverurl';
        $condition['order']      = 'id desc';
        $res                     = $this->findFirst($condition);
        if ($res != false) {
            return $res->toArray();
        }
        return null;
    }


    public function get_wakeup_sms($day, $user_id, $type)
    {
        $time = date('Y-m-d H:i:s', time() - ($day * 24 * 60 * 60));

        $condition['conditions'] = "updated_at > '$time' and is_disable = 0 and referer_id = $user_id";
        switch ($type) {
            case 1:
//                $condition['conditions'] .= "  ";
                break;
            case 2:
                $condition['conditions'] .= "  and is_appuser = 0 ";
                break;
            case 3:
                $condition['conditions'] .= "  and is_appuser = 1 ";
                break;
            case 4:
                $condition['conditions'] .= "  and is_appuser = 0 ";
                break;
            case 5:
                $condition['conditions'] .= "  and is_buyed = 1 ";
                break;
            case 6:
                $condition['conditions'] .= "  and is_buyed = 0 ";
                break;
        }
        $condition['columns'] = 'id,nickname,avatar,phone,updated_at,is_buyed,is_appuser';
        $condition['order']   = 'updated_at asc';
        $wakeup_list          = $this->find($condition)->toArray();

        return ['list' => $wakeup_list, 'count' => count($wakeup_list)];
    }

    /**
     * 获取父级ID
     * @param $user_id
     */
    public function get_user_first_order($user_id)
    {
        $condition['conditions'] = "id = $user_id";
        $condition['columns']    = 'id,referer_id,path,is_buyed';
        return $this->findFirst($condition);
    }

    /**
     * 升级高级运营商成长值
     * @param $type 1每日登录 2邀请粉丝首次登录 3 邀请粉丝首次下单 4间邀粉丝首次登录  5间邀粉丝首次下单 6自购 7粉丝订单 8完成昵称 9微信授权 10绑定支付宝 11填写收货地址 12直邀潜在粉丝注册 13推荐潜在粉丝注册
     * @param $user_id 用户ID
     * @return bool
     */
    public function growth_value($type, $user_id)
    {
        $level['one']   = 1500;
        $level['two']   = 3000;
        $level['order'] = 720;
        $userModel      = $this->find_by_id($user_id);

        if ($userModel->level_id != 1) {
            return false;
        }
        $valModel = new UserGrowthValue();
        $valData  = $valModel->findbyUserId($user_id);
        if (!$valData) {
            $addData['user_id']    = $user_id;
            $addData['created_at'] = date('Y-m-d H:i:s');
            $addData['updated_at'] = date('Y-m-d H:i:s');
            $valModel->save($addData);
            $valData = $valModel->findbyUserId($user_id);
        }
        $inviteVal    = $valData->invite_login_val + $valData->invite_reg_val + $valData->invite_first_order_val;
        $shareVal     = $valData->recommend_login_val + $valData->recommend_reg_val + $valData->recommend_first_order_val;
        $orderVal     = $valData->self_purchase_order_val + $valData->fans_order_val;
        $growth_value = 0;
        $growthTitle  = '';
        switch ($type) {
            case 1:
                $growth_value = 2;
                $growthTitle  = 'login_val';
                break;
            case 2:
                if ($inviteVal >= $level['one']) {
                    return false;
                }
                $growth_value = 15;
                $growthTitle  = 'invite_login_val';
                break;
            case 3:
                if ($inviteVal >= $level['one']) {
                    return false;
                }
                $growth_value = 20;
                $growthTitle  = 'invite_first_order_val';
                break;
            case 4:
                if ($shareVal >= $level['two']) {
                    return false;
                }
                $growth_value = 15;
                $growthTitle  = 'recommend_login_val';
                break;
            case 5:
                if ($shareVal >= $level['two']) {
                    return false;
                }
                $growth_value = 20;
                $growthTitle  = 'recommend_first_order_val';
                break;
            case 6:
                if ($orderVal >= $level['order']) {
                    return false;
                }
                $growth_value = 5;
                $growthTitle  = 'self_purchase_order_val';
                break;
            case 7:
                if ($orderVal >= $level['order']) {
                    return false;
                }
                $growth_value = 5;
                $growthTitle  = 'fans_order_val';
                break;
            case 8:
                if ($valData->name_val > 0) {
                    return false;
                }
                $growth_value = 10;
                $growthTitle  = 'name_val';
                break;
            case 9:
                if ($valData->wechat_val > 0) {
                    return false;
                }
                $growth_value = 10;
                $growthTitle  = 'wechat_val';
                break;
            case 10:
                if ($valData->alipay_val > 0) {
                    return false;
                }
                $growth_value = 10;
                $growthTitle  = 'alipay_val';
                break;
            case 11:
                if ($valData->collect_goods > 0) {
                    return false;
                }
                $growth_value = 10;
                $growthTitle  = 'collect_goods';
                break;
            case 12:
                if ($inviteVal >= $level['one']) {
                    return false;
                }
                $growth_value = 2;
                $growthTitle  = 'invite_reg_val';
                break;
            case 13:
                if ($inviteVal >= $level['two']) {
                    return false;
                }
                $growth_value = 2;
                $growthTitle  = 'recommend_reg_val';
                break;
        }
        $write       = '添加成长值用户ID：' . $userModel->id . ';写入日期:' . date('Y-m-d H:i:s', time()) .';成长值:'.$growth_value.';title:'."$growthTitle\n";
        $create_file = '../cache/growth_value.log';       //创建文件
        file_put_contents($create_file, $write, FILE_APPEND | LOCK_EX);
        if ($growthTitle != '') {
            $valData->$growthTitle += $growth_value;
            $valData->save();

            if ($type == 1) {
                $userModel->sign_time = time();
            }
            $userModel->growth_value += $growth_value;
            $userModel->save();
        }
        return true;
    }

    /**
     * 每日下单加成长值
     */
    public function day_growth_value()
    {
        $order     = new Order();
        $orderData = $order->get_day_growth_val();
        //成长值
        if ($orderData) {
            foreach ($orderData as $key => $val) {
                $count       = count($val);
                $first_order = $this->get_user_first_order($key);
                if ($first_order)
                    //粉丝首次下单
                    if ($first_order->is_buyed == 0) {
                        $this->growth_value(3, $first_order->referer_id);
                        $idArr = explode(",", $first_order->path);
                        $last  = end($idArr);
                        if ($last) {
                            $this->growth_value(5, $last);
                        }
                    } else {
                        //粉丝下单
                        for ($i = 0; $i < $count; $i++) {
                            $this->growth_value(7, $first_order->referer_id);
                        }
                    }

                //自购订单
                for ($i = 0; $i < $count; $i++) {
                    $this->growth_value(6, $key);
                }

            }
        }
        return true;
    }


    /**
     * 是否升级
     */
    public function is_upgrade($user_id)
    {
        $user = $this->find_by_id($user_id);

        $orderComm = new OrderCommissions();
        switch ($user->level_id) {
            case 1://升高运
                $start_end_time = Common::timeChange(5);  //30的收益
                $where          = $orderComm->get_income_month($user_id, $start_end_time);
                $money          = $where['zi_money'] + $where['fen_money'];
                if ($money >= 300 && $user->growth_value == 5000) {
                    $user->level_id     = 2;
                    $user->upgrade_time = date('Y-m-d H:i:s');
                    $user->growth_value = 0;
                    $user->save();

                    //直邀升高创
                    $this->growth_value_ceo(1, $user->referer_id);
                    $idArr = explode(",", $user->path);
                    $last  = end($idArr);
                    //间邀升高创
                    $this->growth_value_ceo(3, $last);
                }
                return true;
            case 2://高运升总裁
                $where = $orderComm->get_senior_income($user_id);
                $money = $where['zi_money'] + $where['fen_money'];
                if ($money >= 20000 && $user->growth_value == 10000) {
                    $user->level_id     = 3;
                    $user->upgrade_time = date('Y-m-d H:i:s');

                    if ($user->referer_id) {
                        $superior = $this->find_by_id($user->referer_id);
                        if ($superior->level_id > 2 && $superior->level_id < 7) {
                            $superior->upgrade_time = date('Y-m-d H:i:s');
                            $superior->level_id     += 1;
                            $superior->save();
                        }
                    }
                    $user->save();
                }
                return true;

            case 3://手动升级总裁 满足条件上级加特权
                if ($user->is_manual_upgrade == 1 && $user->is_satisfy == 0) {
                    $where = $orderComm->get_senior_income($user_id);
                    $money = $where['zi_money'] + $where['fen_money'];
                    if ($money >= 20000 && $user->growth_value == 10000) {
                        $user->is_satisfy = 1;
                        if ($user->referer_id) {
                            $superior = $this->find_by_id($user->referer_id);
                            if ($superior->level_id > 2 && $superior->level_id < 7) {
                                $superior->upgrade_time = date('Y-m-d H:i:s');
                                $superior->level_id     += 1;
                                $superior->save();
                            }
                        }
                        $user->upgrade_time = date('Y-m-d H:i:s');
                        $user->save();
                    }
                }
                return true;
        }

        return false;
    }

    /**
     *
     * 是否升级
     */
    public function is_juyu_upgrade($user_id)
    {

        $model   = (new BUsers());
        $user    = $model->details('user_id=' . $user_id);
        $grade   = 0;
        $upgrade = false;
        $result  = false;
        switch ($user['grade']) {
            case 1://VIP1(初级会员)
                $upgrade = $model->upgradeVip2($user_id);
                if ($upgrade || $user['contribution'] >= 1250) {
                    $upgrade = true;
                    $grade   = 2;
                }
                break;
            case 2://VIP2(中级会员)
                if ($user['contribution'] >= 2500 && $user['contribution'] < 6500) {
                    $upgrade = true;
                    $grade   = 3;
                }
                break;
            case 3://VIP3(高级会员)
                $upgrade = $model->upgradeVip4($user_id);
                if ($upgrade || $user['contribution'] >= 6500 && $user['contribution'] < 20900) {
                    $upgrade = true;
                    $grade   = 4;
                }
                break;
            case 4://CEO4(初级经理)
                $upgrade = $model->upgradeVip5($user_id);
                if ($upgrade || $user['contribution'] >= 20900) {
                    $upgrade = true;
                    $grade   = 5;
                }
                break;
            case 5://CEO5(中级经理)
                $upgrade = $model->upgradeVip6($user_id);
                if ($upgrade) {
                    $upgrade = true;
                    $grade   = 6;
                }
                break;
        }

        if ($upgrade) {
            $user                     = $this->find_by_id($user_id);
            $user->level_id           = $grade;
            $user->level_promotion_at = date('Y-m-d H:i:s', time());
            $user->save();

            $update['grade']      = $grade;
            $update['updated_at'] = date('Y-m-d H:i:s', time());
            $model->findFirst('user_id=' . $user_id)->update($update);
            $result = true;
        }


        return $result;
    }

    /**
     * 高级运营商成长值
     * @param $type 1直邀高级运营商 2直邀高级运营商佣金 3间接邀请高进运营商 4间接高级运营商佣金
     * @param $user_id
     * @return bool
     */
    public function growth_value_ceo($type, $user_id)
    {

        $userModel = $this->find_by_id($user_id);
//        if($userModel->level_id != 2){
//            return false;
//        }
        $valModel = new UserGrowthValue();
        $valData  = $valModel->findbyUserId($user_id);
        if (!$valData) {
            $addData['user_id']    = $user_id;
            $addData['created_at'] = date('Y-m-d H:i:s');
            $addData['updated_at'] = date('Y-m-d H:i:s');
            $valModel->save($addData);
            $valData = $valModel->findbyUserId($user_id);
        }
        switch ($type) {
            case 1:
                if ($valData->invite_senior_operators >= 2000) {
                    return false;
                }
                $valData->invite_senior_operators += 400;
                $userModel->growth_value          += 400;
                break;
            case 2:
                if ($valData->invite_order_commission >= 1000) {
                    return false;
                }
                $valData->invite_senior_operators += 200;
                $userModel->growth_value          += 200;
                break;
            case 3:
                if ($valData->recommend_senior_operators >= 4500) {
                    return false;
                }
                $valData->recommend_senior_operators += 300;
                $userModel->growth_value             += 300;
                break;
            case 4:
                if ($valData->recommend_order_commission >= 3000) {
                    return false;
                }
                $valData->recommend_order_commission += 200;
                $userModel->growth_value             += 200;
                break;
        }
        $valData->save();
        $userModel->save();
        return true;
    }

    /**
     * 高级运营商佣金获取成长值 一个月调一次
     */
    public function get_month_commission()
    {
        $commOrder                = new OrderCommissions();
        $start_end_time           = Common::timeChange(5);  //
        $conditions['conditions'] = " tk_create_time >= '{$start_end_time['start_at']}'  and tk_create_time <= '{$start_end_time['end_at']}' and commission_type = 2 and settlement_type = 1 and order_status= 6";
        $conditions['columns']    = 'sum(money) as money,user_id';
        $conditions['group']      = 'user_id';
        $zi_res                   = $commOrder->find($conditions)->toArray();
        if (!empty($zi_res)) {
            foreach ($zi_res as $val) {
                if ($val['money'] >= 1000) {
                    $userInfo = $this->find_by_id($val['user_id']);
                    if ($userInfo->level_id == 2) {
                        $this->growth_value_ceo(2, $userInfo->referer_id);
                        $idArr = explode(",", $userInfo->path);
                        $last  = end($idArr);
                        if ($last) {
                            $this->growth_value_ceo(4, $last);
                        }
                    }
                }
            }
        }
    }

    //等级名称
    public function get_level_name($level_id)
    {
        $level_obj = new Levels();
        $level_find_one = $level_obj->find_by_id($level_id);
        if($level_find_one){
            return $level_find_one['name'];
        }else{
            return '合伙人';
        }
    }

    //算法等级名称
    public function get_level_name_suan($level_id)
    {
        switch ($level_id) {
            case 1:
                return '运营商';
            case 2:
                return '高级运营商';
            case 3:
                return '总裁';
            case 4:
                return '总裁1';
            case 5:
                return '总裁2';
            case 6:
                return '总裁3';
            case 7:
                return '总裁4';

        }
    }

    //隐藏手机号中间4位
    public function get_phone($phone)
    {
        return substr_replace($phone, '****', 3, 4);
    }

    /**
     * 自己分佣
     * @param $grade //等级
     * @param $id //分佣id
     * @return mixed
     */
    private function selfCommission($grade, $id = '')
    {
        $rate = 0;
        switch ($grade) {
            case 1://VIP1(初级会员)
                $rate = 0;
                break;
            case 2://VIP2(中级会员)
                $rate = 0;
                break;
            case 3://VIP3(高级会员)
                $rate = 0;
                break;
            case 4://CEO4(初级经理)
                $rate = 0.06;
                break;
            case 5://CEO5(中级经理)
                $rate = 0.12;
                break;
            case 6://CEO6(高级经理)
                $rate = 0.18;
                break;
        }
        if ($id) {
            $this->redis->set($id . '_range_' . $grade, 1, 300);
        }
        $this->rate = $rate;
        return $rate;
    }

    /**
     * 父级们分佣
     * @param $directly //是否直属
     * @param $grade //等级
     * @param $id //分佣id
     * @return mixed
     */
    private function parentsCommission($directly, $grade, $id)
    {
        $peer    = $this->redis->get($id . '_peer_' . $grade);//平级
        $range   = $this->redis->get($id . '_range_' . $grade);//级差
        $highest = $this->redis->get($id . '_highest'); // 等级最高
        if (empty($highest) || $grade > $highest) {
            $this->redis->set($id . '_highest', $grade, 300);
            $highest = $grade;
        }
        //最高级获取平级奖 后面将没有平级奖
        if ($this->redis->get($id . '_peer_' . $highest)) {
            $peer = true;
        }
        $rate = 0;
        switch ($grade) {
            case 1://VIP1(初级会员)
                if ($directly) {
                    $rate = 0.01;
                }
                break;
            case 2://VIP2(中级会员)
                if ($directly) {
                    $rate = 0.1;
                }
                break;
            case 3://VIP3(高级会员)
                if ($directly) {
                    $rate = 0.3;
                }
                break;
            case 4://CEO4(初级经理)
                if ($directly) {
                    $rate = 0.3;
                }
                $difference = 0.06 - $this->rate;
                if ($difference > 0) {//级差
                    if (empty($range)) {
                        $rate       += $difference;
                        $this->rate = 0.06;
                        //级差奖励只能一次
                        $this->redis->set($id . '_range_' . $grade, 1, 300);
                    }
                } else if ($difference == 0 && empty($peer)) {//平级
                    $rate += 0.03;
                    //平级奖励只能一次
                    $this->redis->set($id . '_peer_' . $grade, 1, 300);
                }
                break;
            case 5://CEO5(中级经理)
                if ($directly) {
                    $rate = 0.3;
                }
                $difference = 0.12 - $this->rate;
                if ($difference > 0) {//级差
                    if (empty($range)) {
                        $rate       += $difference;
                        $this->rate = 0.12;
                        $this->redis->set($id . '_range_' . $grade, 1, 300);
                    }
                } else if ($difference == 0 && empty($peer)) {//平级
                    $rate += 0.03;
                    $this->redis->set($id . '_peer_' . $grade, 1, 300);
                }
                break;
            case 6://CEO6(高级经理)
                if ($directly) {
                    $rate = 0.3;
                }
                $difference = 0.18 - $this->rate;
                if ($difference > 0) {//级差
                    if (empty($range)) {
                        $rate       += $difference;
                        $this->rate = 0.18;
                        $this->redis->set($id . '_range_' . $grade, 1, 300);
                    }
                } else if ($difference == 0 && empty($peer)) {//平级
                    $rate += 0.03;
                    $this->redis->set($id . '_peer_' . $grade, 1, 300);
                }
                break;
        }
        return $rate;
    }

    //特权等级
    public function get_privilege_list($level)
    {
        $list = [
            2 => [
                'level_name' => '高级运营商',
                'list'       => [
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                ]
            ],
            3 => [
                'level_name' => '总裁',
                'list'       => [
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                    [
                        'icon' => 'icon',
                        'title' => 'title',
                        'details' => 'details',
                    ],
                ]
            ]
        ];
    }

    /**
     * @func 根据id查询
     */
    public function find_by_ids($id)
    {
        $conditions['conditions'] = "invite_code in ($id) or exclusive_code in ($id)";
        $conditions['columns'] = "id";
        $user_info                = $this->find($conditions);
        return $user_info->toarray();
    }

    /**
     * 查找rid和sid是否已经存在
     */
    public function rid_special($tb_rid,$special_id){
        $condition="tb_rid='{$tb_rid}' AND tb_special_id={$special_id}";
        $find_one = $this->findFirst(array(
            $condition,
        ));
        return $find_one;
    }



    /**
     * 获取我团队的粉丝
     */
    public function fans_count($data)
    {
        $conditions = "is_disable=0";
        if (isset($data['path']) && !empty($data['path'])) {
            $conditions .= " AND path like '{$data['path']}%'";
        }
        if (isset($data['referer_id']) && !empty($data['referer_id'])) {
            $conditions .= " AND referer_id = {$data['referer_id']}";
        }
        if (isset($data['indirect_id']) && !empty($data['indirect_id'])) {
            $conditions .= " AND indirect_id = {$data['indirect_id']}";
        }
        //潜在
        if (isset($data['is_appuser'])) {
            $conditions .= " AND is_appuser = 0 ";
        }
        if (isset($data['is_buyed']) && !empty($data['is_buyed'])) {
            $conditions .= " AND is_buyed = {$data['is_buyed']}";
        }
        if (isset($data['created_at_datetime']) && !empty($data['created_at_datetime'])) {
            $conditions .= " AND created_at>='{$data['created_at_datetime']['start_at']}' AND created_at<='{$data['created_at_datetime']['end_at']}'";
        }
        if (isset($data['updated_at_datetime']) && !empty($data['updated_at_datetime'])) {
            $conditions .= " AND updated_at>='{$data['updated_at_datetime']['start_at']}' AND updated_at<='{$data['updated_at_datetime']['end_at']}'";
        }
        $count = $this->count(array(
            $conditions,
            'columns' => 'id',
            'limit'   => 1,
        ));
        return $count;
    }

    /**
     * 总人数
     */
    public function fans_count_num($uid)
    {
        $user_info  = $this->findFirstById($uid);
        $path       = $user_info->path . ',' . $user_info->referer_id . ',' . $uid;
        $conditions = "path like '$path%'";
        return $this->count(array(
            $conditions,
            'column' => 'id',
        ));
    }

    /**
     * 获取我的直邀人数/间邀人数的ids
     */
    public function referer_ids($user_id, $type = 1)
    {
        if ($type == 1) {
            $conditions = "referer_id=$user_id";
        } else {
            $conditions = "indirect_id=$user_id";
        }
        $referer_ids_arr = $this->find(array(
            $conditions,
            'columns' => 'id',
        ))->toarray();
        if ($referer_ids_arr) {
            return implode(',', array_column($referer_ids_arr, 'id'));
        } else {
            return 0;
        }
    }


    /*
     * 我的直推今日下单人数
     * group 是否进行分组查询
     */
    public function referer_today_order($data=[],$group=''){
        $conditions = "is_virtual=0";
        if(isset($data['order_create_time']) && !empty($data['order_create_time'])){
            $conditions .= " AND order_create_time>='{$data['order_create_time']['start_at']}' AND  order_create_time<='{$data['order_create_time']['end_at']}'";
        }
        if(isset($data['referer_ids']) && !empty($data['referer_ids'])){
            $conditions .= " AND user_id in({$data['referer_ids']})";
        }

        if($group){
            $sql_params=[
                $conditions,
                'columns'=>'id',
                'group'=>$group,
            ];
            $order_count = $this->find($sql_params)->toarray();
            return count($order_count);

        }else{
            $sql_params=[
                $conditions,
                'columns'=>'id',
                'limit'=>1,
            ];
            $order_count = $this->count($sql_params);
        }

        return $order_count;
    }

    /**
     * 最近没有登录app的用户
     */
    public function fans_count_nologin($data)
    {
        $conditions = "is_disable=0";
        if (isset($data['path']) && !empty($data['path'])) {
            $conditions .= " AND path like '{$data['path']}%'";
        }
        if (isset($data['referer_id']) && !empty($data['referer_id'])) {
            $conditions .= " AND referer_id = {$data['referer_id']}";
        }
        if (isset($data['is_buyed']) && !empty($data['is_buyed'])) {
            $conditions .= " AND is_buyed = {$data['is_buyed']}";
        }
        if (isset($data['indirect_id']) && !empty($data['indirect_id'])) {
            $conditions .= " AND indirect_id = {$data['indirect_id']}";
        }
        if (isset($data['created_at_datetime']) && !empty($data['created_at_datetime'])) {
            $conditions .= " AND created_at>='{$data['created_at_datetime']['start_at']}' AND created_at<='{$data['created_at_datetime']['end_at']}'";
        }
        if (isset($data['updated_at_datetime']) && !empty($data['updated_at_datetime'])) {
            $conditions .= " AND updated_at<='{$data['updated_at_datetime']['start_at']}'";
        }
        $count = $this->count(array(
            $conditions,
            'columns' => 'id',
            'limit'   => 1,
        ));
        return $count;
    }



    /**
     * 粉丝详情
     */
    public function fans_details($uid)
    {
        $where['conditions'] = "id = $uid";
        $where['columns']    = "avatar,nickname,updated_at,invite_code,referer_id,indirect_id,path,created_at";
        $info                = $this->findFirst($where);
        $result['user_info']=$info->toarray();
        $where['conditions'] = "id = {$info->referer_id}";
        $reinfo                              = $this->findFirst($where);
        $result['user_info']['referer_name'] = $reinfo->nickname;

        //直邀
        $rdata['referer_id']        = $uid;
        $result['fans_referer_num'] = $this->fans_count($rdata);
        //间邀
        $idata['indirect_id']        = $uid;
        $result['fans_indirect_num'] = $this->fans_count($idata);

        //总粉丝
        $pdata['path']           = $info->path;
        $result['fans_num']      = $this->fans_count_num($uid);
        $result['fans_num']      += $result['fans_referer_num'];
        $f_user_order_statistics = new OrderCommissions();
        //今天
        $today             = Common::timeChange(1);
        $todayNum                 = $f_user_order_statistics->getOrderSettlementCommission_new3($uid, $today);
        $result['today_estimate'] = Common::number_randtwo($todayNum);

        //昨天
        $yesterday             = Common::timeChange(2);
        $todayNum                     = $f_user_order_statistics->getOrderSettlementCommission_new3($uid, $yesterday);
        $result['yesterday_estimate'] = Common::number_randtwo($todayNum);

        //本月
        $thisMonth                    = Common::timeChange(8);
        $todayNum                     = $f_user_order_statistics->getOrderSettlementCommission_new3($uid, $thisMonth);
        $result['thisMonth_estimate'] = Common::number_randtwo($todayNum);

        //上月
        $lastMonth                    = Common::timeChange(9);
        $todayNum                     = $f_user_order_statistics->getOrderSettlementCommission_new3($uid, $lastMonth);
        $result['lastMonth_estimate'] = Common::number_randtwo($todayNum);
        $incon            = new UserMonthIncome();
        $result['income'] = $incon->get_all_income($uid);
        return $result;
    }

}
